package com.angzh.bolibao.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.angzh.bolibao.common.MD5Util;
import com.angzh.bolibao.common.Util;
import com.angzh.bolibao.model.Clicks;
import com.angzh.bolibao.model.Commission;
import com.angzh.bolibao.model.Customer;
import com.angzh.bolibao.model.User;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

public class UserController extends Controller{
	private static final Logger log = Logger.getLogger(UserController.class);
	public void index(){
		render("/pages/login/login.jsp");
	}
	public void login(){
		String userName = getPara("username");
		String password = getPara("password");
		Map<String, Object> retJson = Util.getRetJson();
		do{
			if(StrKit.isBlank(userName)){
				retJson = Util.getErrorRetJson("用户名不能为空！");
				break;
			}
			if(StrKit.isBlank(password)){
				retJson = Util.getErrorRetJson("密码不能为空！");
				break;
			}
			final User adminN = User.dao.getUserByUserName(userName);
			if(adminN == null){
				retJson = Util.getErrorRetJson("用户不存在");
				break;
			}
			password = MD5Util.encrypt(password);
			final User adminP = User.dao.getUserByLogin(userName, password);
			if(adminP == null){
				retJson = Util.getErrorRetJson("密码错误");
				break;
			}
			retJson = Util.getOkRetJson("登陆成功");
			log.info("用户" + userName + "登陆成功");
			HttpSession session = getSession(true);
			if(session == null){
				log.info("session 创建失败");
				throw new RuntimeException("session 创建失败"); 
			}
			session.setAttribute("admin", adminP);
			if(adminP.getInt("role")==1){
				retJson.put("url", "/user/group");
			} else if(adminP.getInt("role")==2){
				retJson.put("url", "/user/company");
			}else if(adminP.getInt("role")==3){
				retJson.put("url", "/user/workerIndex");
			}else if(adminP.getInt("role")==4){
				retJson.put("url", "/customer/peifulist");
			}
		}while(false);
		renderJson(retJson); 
	}
	public void logout(){
		HttpSession session = getSession();
		if(session != null){
			session.invalidate();
		}
		render("/pages/login/login.jsp");
	}
	public void saveCompany(){
		User user = getModel(User.class);
		String password = user.getStr("password");
		String encryptPS = MD5Util.encrypt(password);
		user.set("password", encryptPS);
		if(user.get("id")!=null&&!user.get("id").equals("")){
			user.update();
		}else{
			user.save();
		}
		redirect("/user/group");
	}
	//新增修改用户信息
	public void modifyInfo(){
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		int role = user.getInt("role");
		String phone = getPara("phone");
		String address = getPara("address");
		user.set("phone", phone);
		user.set("address", address);
		user.update();
		setAttr("msg","更新成功！");
		if(role==1){
			render("/pages/group/modifyInfo.jsp");
		}else if(role==2){
			render("/pages/company/modifyInfo.jsp");
		}else if(role==4){
			render("/pages/service/modifyInfo.jsp");
		}
	}
	public void saveWorker(){
		User user = getModel(User.class);
		String password = user.getStr("password");
		String encryptPS = MD5Util.encrypt(password);
		user.set("password", encryptPS);
		if(user.get("id")!=null&&!user.get("id").equals("")){
			user.update();
		}else{
			user.save();
		}
		HttpSession session = getSession(true);
		User admin = (User)session.getAttribute("admin");
		if(admin.getInt("role")==1){
			redirect("/user/worker");
		}else if(admin.getInt("role")==2){
			redirect("/user/company");
		}
	}
	
	//修改密码
	public void modifyPassword(){
		int id = getParaToInt("id");
		String username = getPara("username");
		String password = getPara("password");
		int role = getParaToInt("role");
		User user = User.dao.findById(id);
		String encryptPS = MD5Util.encrypt(password);
		user.set("password", encryptPS);
		
		//以上为管理员操作，下面是商家操作。
		try{
			user.update();
			setAttr("msg","修改成功！");
		}catch(Exception e){
			e.printStackTrace();
			setAttr("msg","修改失败！");
		}
		if(role==1){
			render("/pages/group/modifypassword.jsp");
		}else if(role==2){
			render("/pages/company/modifypassowrd.jsp");
		}else if(role==3){
			render("/pages/worker/modifypassword.jsp");
		}else if(role==4){
			render("/pages/service/modifypassword.jsp");
		}
	}
	//绑定微信
	public void linkWeichat(){
		User user = getModel(User.class);
		user.update();
		String weichat = user.getStr("weichat");
		HttpSession session = getSession(true);
		User admin = (User)session.getAttribute("admin");
		admin.set("weichat", weichat);
		session.setAttribute("admin", admin);
		setAttr("msg","绑定成功！");
		render("/pages/worker/weichat.jsp");
		
	}
	//集团首页(公司账号列表)
	public void group(){
		int pageNum = Integer.parseInt(getPara("pageNum")==null?"1":getPara("pageNum"));
		int pageSize = Integer.parseInt(getPara("pageSize")==null?"12":getPara("pageSize"));
		setAttr("userPage", User.dao.paginate(pageNum, pageSize,2));
		render("/pages/group/companyList.jsp");
	}
	//员工账号列表
	public void worker(){
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		String company = user.getStr("company");
		int pageNum = Integer.parseInt(getPara("pageNum")==null?"1":getPara("pageNum"));
		int pageSize = Integer.parseInt(getPara("pageSize")==null?"12":getPara("pageSize"));
		setAttr("userPage", User.dao.paginate(pageNum, pageSize,3,company));
		render("/pages/group/workerList.jsp");
	}
	//删除帐号
	public void delete(){
		int type = getParaToInt("type");
		int id = getParaToInt("id");
		User.dao.deleteById(id);
		if(type==0){
			redirect("/user/group");
		}else if(type==1){
			redirect("/user/worker");
		}else if(type==2){
			redirect("/user/company");
		}
	}
	//分公司员工列表
	public void company(){
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		String company = user.getStr("company");
		int pageNum = Integer.parseInt(getPara("pageNum")==null?"1":getPara("pageNum"));
		int pageSize = Integer.parseInt(getPara("pageSize")==null?"12":getPara("pageSize"));
		setAttr("userPage", User.dao.paginate(pageNum, pageSize,3,company));
		render("/pages/company/workerList.jsp");
	}
	//跳转员工帐号登录主界面
	public void workerIndex(){
		String startTime = getPara("startTime")==null?"":getPara("startTime");
		String endTime = getPara("endTime")==null?"":getPara("endTime");
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		String weichat = user.getStr("weichat");
		List<Customer> customer1 = Customer.dao.totalCommission(startTime, endTime, weichat, 1);
		int type1num = 0;
		if(customer1!=null){
			type1num = customer1.size();
		}
		List<Customer> customer2 = Customer.dao.totalCommission(startTime, endTime, weichat, 2);
		int type2num = 0;
		if(customer2!=null){
			type2num= customer2.size();
		}
		List<Customer> customer3 = Customer.dao.totalCommission(startTime, endTime, weichat, 3);
		int type3num = 0;
		if(customer3!=null){
			type2num= customer3.size();
		}
		float totalprice = type1num * 200 + type2num * 400 + type3num * 1000;
		
		String companyname = user.getStr("company");
		User company = User.dao.getCompanyByName(2, companyname);
		int companyId = company.getInt("id");
		Commission c = Commission.dao.getCommission(2,companyId);
		float percent1 = 0;
		float percent2 = 0;
		float percent3 = 0;
		if(c!=null){
			percent1 = c.getFloat("percent1")==null?0:c.getFloat("percent1");
			percent2 = c.getFloat("percent2")==null?0:c.getFloat("percent2");
			percent3 = c.getFloat("percent3")==null?0:c.getFloat("percent3");
		}
		float totalCommission = type1num * 200 * percent1 + type2num * 400 * percent2+type3num * 1000 * percent3;
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		
		map.put("type1num", type1num);
		
		map.put("type2num", type2num);
		map.put("type3num", type3num);
		map.put("totalprice", totalprice);
		map.put("totalcommission", totalCommission);
		setAttr("data",map);
		render("/pages/worker/statistics.jsp");
	}
	//员工客户列表
	public void listbyworker(){
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		String weichat = user.getStr("weichat");
		int pageNum = Integer.parseInt(getPara("pageNum")==null?"1":getPara("pageNum"));
		int pageSize = Integer.parseInt(getPara("pageSize")==null?"12":getPara("pageSize"));
		setAttr("userPage", User.dao.paginate(pageNum, pageSize,3,weichat));
		render("/pages/worker/customer.jsp");
	}
	//集团员工佣金统计
	public void workerStatistics(){
		List list = new ArrayList();
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		String company = user.getStr("company");
		List<User> userlist = User.dao.userList(3, company);
		setAttr("userlist",userlist);
		String startTime = getPara("startTime")==null?"":getPara("startTime");
		String endTime = getPara("endTime")==null?"":getPara("endTime");
		String weichat = getPara("weichat")==null?"":getPara("weichat");
		int total200=0,total400=0,total1000=0, totalclicks=0;
		float totalprice = 0,totalCommission=0;
		if(weichat.equals("")){
			for(int i=0;i<userlist.size();i++){
				weichat = userlist.get(i).getStr("weichat");
				if(weichat!=null && !weichat.equals("")){
					Map<String,Object> map = new HashMap<String,Object>();
					map = this.getTotalCommission(startTime, endTime, weichat);
					total200 += Integer.parseInt(map.get("type1num").toString());
					total400 += Integer.parseInt(map.get("type2num").toString());
					total1000 += Integer.parseInt(map.get("type3num").toString());
					totalprice += Float.parseFloat(map.get("totalprice").toString());
					totalCommission += Float.parseFloat(map.get("totalcommission").toString());
					map.put("user", userlist.get(i).get("name"));
					int clicks = Clicks.dao.getClicks(weichat, startTime, endTime).getNumber("count").intValue();
					totalclicks += clicks;
					map.put("user", userlist.get(i).get("name"));
					map.put("clicks", clicks);
					list.add(map);
				}
			}
			Map<String,Object> mapAll = new HashMap<String,Object>();
			mapAll.put("user", "员工合计");
			mapAll.put("startTime", startTime);
			mapAll.put("endTime", endTime);
			
			mapAll.put("type1num", total200);
			mapAll.put("type2num", total400);
			mapAll.put("type3num", total1000);
			mapAll.put("totalprice", totalprice);
			mapAll.put("totalcommission", totalCommission);
			mapAll.put("clicks", totalclicks);
			list.add(mapAll);
			Commission c2 = Commission.dao.getCommission(1, -1);
			float percent11 = 0;
			float percent22 = 0;
			float percent33 = 0;
			if(c2!=null){
				percent11 = c2.getFloat("percent1")==null?0:c2.getFloat("percent1");
				percent22 = c2.getFloat("percent2")==null?0:c2.getFloat("percent2");
				percent33 = c2.getFloat("percent3")==null?0:c2.getFloat("percent3");
				totalCommission = 200 * total200 * percent11 + 400 * total400 * percent22 + 1000*total1000*percent33;
			}
			Map<String,Object> mapOwn = new HashMap<String,Object>();
			mapOwn.put("user", "公司合计");
			mapOwn.put("startTime", startTime);
			mapOwn.put("endTime", endTime);
			
			mapOwn.put("type1num", total200);
			mapOwn.put("type2num", total400);
			mapOwn.put("type3num", total1000);
			mapOwn.put("totalprice", totalprice);
			mapOwn.put("totalcommission", totalCommission);
			mapAll.put("clicks", totalclicks);
			list.add(mapOwn);
		}else{
			Map<String,Object> map = new HashMap<String,Object>();
			map = this.getTotalCommission(startTime, endTime, weichat);
			User worker = User.dao.getUserByWeichat(weichat);
			map.put("user", worker.get("name"));
			int clicks = Clicks.dao.getClicks(weichat, startTime, endTime).getNumber("count").intValue();
			map.put("clicks", clicks);
			list.add(map);
		}
		setAttr("list",list);
		render("/pages/group/companyStatistics.jsp");
	}
	//集团分公司佣金统计
	public void groupStatistics(){
		String startTime = getPara("startTime")==null?"":getPara("startTime");
		String endTime = getPara("endTime")==null?"":getPara("endTime");
		List<User> userList = User.dao.companyList();
		List list = new ArrayList();
		Commission commission = Commission.dao.getCommission(1, -1);
		for(User user : userList){
			String company = user.get("company");
			
			Record data200 = User.dao.companyCommission(company, 1,startTime,endTime);
			long count200 = data200.getLong("count");//200元单数
			float percent200 = commission.getFloat("percent1");//200元佣金比例
			
			Record data400 = User.dao.companyCommission(company,2,startTime,endTime);
			long count400 = data400.getLong("count");//400元单数
			float percent400 = commission.getFloat("percent2");//400元佣金比例
			
			Record data1000 = User.dao.companyCommission(company,3,startTime,endTime);
			long count1000 = data1000.getLong("count");//1000元单数
			float percent1000 = commission.getFloat("percent3");//1000元佣金比例
			
			long totalprice = count200 * 200 + count400 * 400;
			float totalCommission = count200 * 200 * percent200 + count400 * 400 * percent400+count1000*1000*percent1000;
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("company", company);
			map.put("startTime", startTime);
			map.put("endTime", endTime);
			map.put("count200", count200);
			map.put("count400", count400);
			map.put("count1000", count1000);
			map.put("totalprice", totalprice);
			map.put("totalCommission", totalCommission);
			list.add(map);
		}
		setAttr("companyList",list);
		setAttr("startTime",startTime);
		setAttr("endTime",endTime);
		render("/pages/group/statisticsGroup.jsp");
	}
	//分公司佣金统计导出
	public void export() throws FileNotFoundException{
		Date d=new Date();  
	    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");  
	    String title=dateFormat.format(d);  
	    System.out.println(title);  
	    File file = new File(title+"_统计表"+".xls");  
	    HSSFWorkbook hssfWorkbook = new HSSFWorkbook();  
        // sheet:一张表的简称  
        // row:表里的行  
        // 创建工作薄中的工作表  
        HSSFSheet hssfSheet = hssfWorkbook.createSheet("test");  
        // 创建表头行  
        HSSFRow rowHead = hssfSheet.createRow(0);  
        // 创建单元格，设置表头 创建列  
        CellStyle style = hssfWorkbook.createCellStyle();//新建样式对象
        style.setBorderBottom(HSSFColor.BLUE.index);
        style.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
        rowHead.createCell(0).setCellValue("公司名称");
        rowHead.getCell(0).setCellStyle(style);
        rowHead.createCell(1).setCellValue("开始时间");
        rowHead.getCell(1).setCellStyle(style);
        rowHead.createCell(2).setCellValue("结束时间");
        rowHead.getCell(2).setCellStyle(style);
        rowHead.createCell(3).setCellValue("200元单数");
        rowHead.getCell(3).setCellStyle(style);
        rowHead.createCell(4).setCellValue("400元单数");
        rowHead.getCell(4).setCellStyle(style);
        rowHead.createCell(5).setCellValue("1000元单数");
        rowHead.getCell(5).setCellStyle(style);
        rowHead.createCell(6).setCellValue("成交金额");
        rowHead.getCell(6).setCellStyle(style);
        rowHead.createCell(7).setCellValue("公司所得佣金");
        rowHead.getCell(7).setCellStyle(style);
		String startTime = getPara("startTime")==null?"":getPara("startTime");
		String endTime = getPara("endTime")==null?"":getPara("endTime");
		List<User> userList = User.dao.companyList();
		Commission commission = Commission.dao.getCommission(1, -1);
		int i=1;
		for(User user : userList){
			HSSFRow row = hssfSheet.createRow(i);  
			String company = user.get("company");
			Record data200 = User.dao.companyCommission(company, 1,startTime,endTime);
			long count200 = data200.getLong("count");//200元单数
			float percent200 = commission.getFloat("percent1");//200元佣金比例
			
			Record data400 = User.dao.companyCommission(company,2,startTime,endTime);
			long count400 = data400.getLong("count");//400元单数
			float percent400 = commission.getFloat("percent2");//400元佣金比例
			
			Record data1000 = User.dao.companyCommission(company,3,startTime,endTime);
			long count1000 = data1000.getLong("count");//1000元单数
			float percent1000 = commission.getFloat("percent3");//1000元佣金比例
			
			long totalprice = count200 * 200 + count400 * 400 + count1000*1000;
			float totalCommission = count200 * 200 * percent200 + count400 * 500 * percent400+count1000*1000*percent1000;
			
			row.createCell(0).setCellValue(company);
			
			row.createCell(1).setCellValue(startTime);
			
			row.createCell(2).setCellValue(endTime);
			
			row.createCell(3).setCellValue(count200);
			
			row.createCell(4).setCellValue(count400);
			
			row.createCell(5).setCellValue(count1000);
			
			row.createCell(6).setCellValue(totalprice);
			
			row.createCell(7).setCellValue(totalCommission);
			
			i++;
			
		}
		 try {  
	            FileOutputStream fileOutputStreane = new FileOutputStream(file);  
	            hssfWorkbook.write(fileOutputStreane);  
	            fileOutputStreane.flush();  
	            fileOutputStreane.close();  
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
		 renderFile(file);
	}
	public Map<String, Object> getTotalCommission(String startTime,String endTime,String weichat){
		List<Customer> customer1 = Customer.dao.totalCommission(startTime, endTime, weichat, 1);
		int type1num = 0;
		if(customer1!=null){
			type1num = customer1.size();
		}
		List<Customer> customer2 = Customer.dao.totalCommission(startTime, endTime, weichat, 2);
		int type2num = 0;
		if(customer2!=null){
			type2num= customer2.size();
		}
		List<Customer> customer3 = Customer.dao.totalCommission(startTime, endTime, weichat, 3);
		int type3num = 0;
		if(customer3!=null){
			type3num= customer3.size();
		}
		float totalprice = type1num * 200 + type2num * 400 + type3num * 1000;
		HttpSession session = getSession(true);
		User user = (User)session.getAttribute("admin");
		int companyId = user.getInt("id");
		Commission c = Commission.dao.getCommission(2,companyId);
		float percent1 = 0;
		float percent2 = 0;
		float percent3 = 0;
		if(c!=null){
			percent1 = c.getFloat("percent1")==null?0:c.getFloat("percent1");
			percent2 = c.getFloat("percent2")==null?0:c.getFloat("percent2");
			percent3 = c.getFloat("percent3")==null?0:c.getFloat("percent3");
		}
		Commission c2 = Commission.dao.getCommission(1, companyId);
		float percent11 = 0;
		float percent22 = 0;
		float percent33 = 0;
		if(c2!=null){
			percent11 = c2.getFloat("percent1")==null?0:c.getFloat("percent1");
			percent22 = c2.getFloat("percent2")==null?0:c.getFloat("percent2");
			percent33 = c2.getFloat("percent3")==null?0:c.getFloat("percent3");
		}
		float totalCommission = type1num * 200 * percent1 * percent11 + type2num * 400 * percent2 * percent22 + type3num*1000*percent3*percent33;
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		map.put("type1num", type1num);
		map.put("type2num", type2num);
		map.put("type3num", type3num);
		map.put("totalprice", totalprice);
		map.put("totalcommission", totalCommission);
		return map;
	}
}
